package com.petrochina.cloudconfig.job;


import com.petrochina.cloudconfig.domain.DeployServer;
import com.petrochina.cloudconfig.mapper.ServerMapper;
import com.petrochina.cloudconfig.util.ServerUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.*;

@Component
public class ServerCheckJob {

    @Autowired
    private ServerMapper serverMapper;


    @Autowired
    private StringRedisTemplate redisTemplate;


    private static final String REDIS_KEY="servers";


    @Scheduled(fixedDelay = 5*1000)
    public void check(){
        Map<Object, Object> entries = redisTemplate.opsForHash().entries(REDIS_KEY);
        if(entries!=null) {
            Set<Object> keys = entries.keySet();
            for (Object key : keys){
                boolean canConn = ServerUtil.checkIpCanConn(key.toString());
                redisTemplate.opsForHash().put(REDIS_KEY,key, canConn==true?"1":"0");
            }
        }


    }

    private int checkIP(String ip) {
        int result = 0;

        return result;
    }

    @Scheduled(fixedDelay = 10*1000)
    public void updateServers(){
        List<DeployServer> deployServers = serverMapper.list(null);
        Map<Object, Object> redisEntries = redisTemplate.opsForHash().entries(REDIS_KEY);
        if(redisEntries!=null && redisEntries.size()>0){
            Set<Object> keys = redisEntries.keySet();
            List<Object> needRemoveKeys = new ArrayList<>();
            Set<Object> existKeys = new HashSet<>();
            Map<Object, Object> needAddKvMap = new HashMap<>();
            for (int i = 0; i < deployServers.size(); i++) {
                String serverIp = deployServers.get(i).getServerIp();
                if(redisEntries.get(serverIp)==null){
                    needAddKvMap.put(serverIp,"0");
                }else{
                    existKeys.add(serverIp);
                }
            }
            for (Object key : keys){
                if(!existKeys.contains(key)){
                    needRemoveKeys.add(key);
                }
            }
            if(needRemoveKeys.size()>0){
                redisTemplate.opsForHash().delete(REDIS_KEY,needRemoveKeys.toArray());
            }
            if(needAddKvMap.size()>0){
                redisTemplate.opsForHash().putAll(REDIS_KEY,needAddKvMap);
            }

        }else{
            Map<Object, Object> needAddKvMap = new HashMap<>();
            for (int i = 0; i < deployServers.size(); i++) {
                needAddKvMap.put(deployServers.get(i).getServerIp(),"0");
            }
            if(needAddKvMap.size()>0){
                redisTemplate.opsForHash().putAll(REDIS_KEY,needAddKvMap);
            }

        }



    }
}
